import React, { useState, useEffect } from 'react';
import {
  getChinaMarketStatus,
  formatMarketStatus,
  getNextTradingTime,
  MarketStatus,
} from '@shared/utils/marketStatus';

const MarketStatusIndicator: React.FC = () => {
  const [status, setStatus] = useState<MarketStatus>(getChinaMarketStatus());
  const [nextTime, setNextTime] = useState<Date | null>(getNextTradingTime());

  // 每30秒更新一次市场状态
  useEffect(() => {
    const interval = setInterval(() => {
      setStatus(getChinaMarketStatus());
      setNextTime(getNextTradingTime());
    }, 30000);

    return () => clearInterval(interval);
  }, []);

  const getStatusColor = (status: MarketStatus) => {
    switch (status) {
      case 'trading':
        return 'bg-green-100 text-green-800 border-green-300';
      case 'pre_market':
        return 'bg-yellow-100 text-yellow-800 border-yellow-300';
      case 'after_hours':
        return 'bg-orange-100 text-orange-800 border-orange-300';
      case 'closed':
        return 'bg-gray-100 text-gray-600 border-gray-300';
      default:
        return 'bg-gray-100 text-gray-600 border-gray-300';
    }
  };

  const getStatusIcon = (status: MarketStatus) => {
    switch (status) {
      case 'trading':
        return '🟢';
      case 'pre_market':
        return '🟡';
      case 'after_hours':
        return '🟠';
      case 'closed':
        return '⚫';
      default:
        return '⚪';
    }
  };

  return (
    <div
      className={`inline-flex items-center gap-2 px-4 py-2 rounded-lg border-2 ${getStatusColor(
        status
      )}`}
    >
      <span className="text-lg">{getStatusIcon(status)}</span>
      <div className="flex flex-col">
        <span className="font-semibold text-sm">
          A股市场：{formatMarketStatus(status)}
        </span>
        {status !== 'trading' && nextTime && (
          <span className="text-xs opacity-75">
            下一交易时段：
            {nextTime.toLocaleString('zh-CN', {
              month: 'short',
              day: 'numeric',
              hour: '2-digit',
              minute: '2-digit',
            })}
          </span>
        )}
      </div>
    </div>
  );
};

export default MarketStatusIndicator;


